package gxprod.androidai.functions;

import gxprod.androidai.BubbleAdapter;
import gxprod.androidai.Unit;
import gxprod.androidai.regex.MatchResult;
import gxprod.androidai.regex.NamedPattern;

public class ConversionFunction extends Function {

	NamedPattern[] patterns = new NamedPattern[] {
			NamedPattern.compile("how many(( [a-z]*?){1,2}?) are in (a|[\\d\\.]+)(( \\w*){1,2})"),
			NamedPattern.compile("convert ([\\d\\.]+)(( [a-z]+?){1,2}) to(( [a-z]+){1,2})")
	};

	@Override
	public boolean cullFunction(String command) { return true; }
	@Override
	public MatchResult isMatch(String statement) {
		return super.isMatch(statement, patterns, 0.64f);
	}

	@Override
	public boolean execute(MatchResult match, BubbleAdapter adapter) {

		String unit1, unit2, value;

		switch(match.MatchIndex) {

			case 0:
				unit1 = match.Matcher.group(1).trim();
				unit2 = match.Matcher.group(4).trim();
				value = match.Matcher.group(3);
				break;
			case 1:
				unit1 = match.Matcher.group(2).trim();
				unit2 = match.Matcher.group(4).trim();
				value = match.Matcher.group(1);
				break;
			default:
				return false;
		}
		Unit u1 = Unit.find(unit1);
		Unit u2 = Unit.find(unit2);
		Double val;
		try { val= Double.parseDouble(value);
		} catch(Exception ex) {
			if(value.equals("a"))
				val = 1.0;
			else 
				val = null;
		}

		if(u1 == null) {
			adapter.output("I dont recognise the unit " + unit1);
		} else if(u2 == null) {
			adapter.output("I dont recognise the unit " + unit2);
		} else if(val == null) {
			adapter.output("I dont know how to use the value " + value);
		} else if (!u1.isOfSameType(u2)) {
			adapter.output("I cant convert from " + unit1 + " to " + unit2);
		} else {
			double converted = u1.convert(val, u2);

			String v;
			if(((float)converted) == ((int)converted))
				v = "" +(int)converted;
			else
				v = "" + (float)converted;

			StringBuilder sb = new StringBuilder();
			if(val == 1.0) {
				sb.append(val);
				sb.append(' ');
			} else
				sb.append("a ");
			sb.append(u1.name());
			if(val != 1)
				sb.append('s');
			sb.append(" is equal to ");
			sb.append(v);
			sb.append(' ');
			sb.append(u2);
			sb.append('s');

			adapter.output(sb.toString(), v);
			return true;
		}
		return false;
	}
}
